package com.zoro.dyformservice.utils.jpa;

import org.springframework.data.jpa.domain.Specification;

import java.util.Date;

public class WhereMakerUtils {

    public static <T> Specification<T> is(String attrName, String value) {
        if (value == null) {
            return (root, query, criteriaBuilder) -> criteriaBuilder.isNull(root.get(attrName));
        }
        return (root, query, builder) -> builder.equal(root.get(attrName), value);
    }

    public static <T> Specification<T> like(String attrName, String value) {
        if (value == null || value.isEmpty()) {
            throw new NullPointerException("can't use null value for like operation");
        }

        return (root, query, criteriaBuilder) -> criteriaBuilder.like(root.get(attrName), value);
    }

    public static <T> Specification<T> range(String attrName, Date start, Date end) {
        if (start == null && end == null) {
            throw new NullPointerException("start and end can not be null both.");
        }
        if (start != null && end != null) {
            return (root, query, criteriaBuilder) -> criteriaBuilder.between(root.get(attrName), start, end);
        }
        if (end == null) {
            return (root, query, criteriaBuilder) -> criteriaBuilder.greaterThan(root.get(attrName), start);
        }
        return (root, query, criteriaBuilder) -> criteriaBuilder.lessThan(root.get(attrName), end);

    }
}
